<template>
	<view class="mbti-group-detail" v-if="isOpen">
		<mBack ref="mBack" @getGameResult="handleBack" v-if="!hideBack"></mBack>
		<view class="mbti-group-detail-content flex-column-start-center" :style="{'background-image': `url(${bgUrl})`}">
			<view class="top-box" :style="{height:contentTop+'rpx'}"></view>
			<view class="content-box flex-column-start-center">
				<view class="group-member-list flex-row-start-center">
					<view class="group-member-item" v-for="(item,index) in memberList" :key="index">
						<view class="group-member-avatar">
							<image class="cover-img" style="border-radius: 50%;" :src="item.avatar" mode="aspectFill">
							</image>
							<view class="group-mbti-avatar flex-row-center-center">
								<image class="cover-img" style="border-radius: 50%;" :src="item.mbtiAvatar"
									mode="aspectFill"></image>
							</view>
						</view>

						<view class="member-name">
							<view class="member-name-content postion-center-center">
								{{item.name}}
							</view>
						</view>
					</view>
					<view class="group-member-item" @click="handleControlBtnClick(citem.type)"
						v-for="(citem,cindex) in controlList" :key="cindex">
						<view class="group-member-avatar">
							<image class="cover-img" style="border-radius: 50%;" :src="citem.icon" mode="aspectFill">
							</image>
						</view>
						<view class="member-name">
						</view>
					</view>
				</view>
				<view class="group-set">
					<view class="group-set-item flex-row-start-center">
						<view class="group-set-item-content flex-row-between-center">
							<view class="group-set-item-inner flex-row-between-center">
								<view class="group-set-item-label flex-row-center-center">拍拍组名</view>
								<view class="group-set-item-text group-set-item-text-value flex-row-end-center"
									@click="handleControlBtnClick('settingGroupName')">
									{{groupName}}
								</view>
							</view>
							<view class="right-control-icon flex-row-center-center" style="margin-right: 4rpx;"
								@click="handleControlBtnClick('settingGroupName')">
								<image
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/e9d6c0cf96c5447f968c5db37a1fb279.png"
									class="cover-img" mode="aspectFill"></image>
							</view>
						</view>

					</view>
					<view class="group-set-item flex-row-start-center">
						<view class="group-set-item-content flex-row-between-center">
							<view class="group-set-item-inner flex-row-between-center">
								<view class="group-set-item-label flex-row-center-center">置顶拍拍</view>
								<view class="group-set-item-text group-set-item-text-value flex-row-end-center">
									<view class="group-choose-btn" :class="{'btn-choosed':isChoosed}"
										@click.stop="handleGroupChooseClick"></view>
								</view>
							</view>
							<view class="right-control-icon flex-row-center-center" style="margin-right: 4rpx;">
								<image
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/e9d6c0cf96c5447f968c5db37a1fb279.png"
									class="cover-img" mode="aspectFill"></image>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="group-bottom-control flex-row-center-center">
				<view class="group-bottom-control-content flex-row-center-center" :class="{'group-create':!id}"
					@click="handleBottomBtnClick">
					<text v-if="id">解散该组</text>
					<text v-else>创建分组</text>
				</view>
			</view>
		</view>
		<mbtiModal ref="mbtiModal" @confirm="handleDeleteConfirm" @close="this.hideBack=false"
			@cancel="handleModalCancel"></mbtiModal>
		<mbtiPop ref="mbtiPop" @confirmValue="handleSettingConfirm" @cancel="handlePopCancel"
			@callBack="handlePopCallBack">
			<view class="firend-list" v-if="(actControlType=='add')||(actControlType=='sub')">
				<scroll-view ref="scrollView" :scroll-y="true" class="scroll-content" :show-scrollbar="false"
					:scroll-with-animation="true">
					<view class="firend-list-content flex-column-start-center">
						<view class="firend-item flex-row-start-center" v-for="(item,index) in addOrSubData"
							:key="index" @click="handleAddOrSubGroup(item,index)">
							<view class="firend-avatar">
								<image class="cover-img" style="border-radius: 50%" :src="item.avatar"
									mode="aspectFill"></image>
							</view>
							<view class="firend-name">{{item.name}}{{actControlType}}</view>
							<view class="firend-control" v-if="actControlType=='add'">

								<image class="cover-img" style="border-radius: 50%;"
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/8c4d7e139ed8494b8848ce547c4ba331.png"
									mode="aspectFill"
									v-if="!oldMemberIds.includes(item.id)&&!newAddMemberIds.includes(item.id)"></image>

								<image class="cover-img" style="border-radius: 50%;"
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7cf6f4b37b1c45ca90e863865a2734d7.png"
									mode="aspectFill" :style="{'opacity':oldMemberIds.includes(item.id)?0.5:1}" v-else>
								</image>

							</view>
							<!--  -->
							<view class="firend-control" v-if="actControlType=='sub'">
								<image class="cover-img" style="border-radius: 50%;"
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/d2d73962b6714f53bf332d59f1adcced.png"
									mode="aspectFill" v-if="subMemberIds.includes(item.id)"></image>
								<image class="cover-img" style="border-radius: 50%;"
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/e65735d4bf9a4f80ac999159404a60b0.png"
									mode="aspectFill" v-else></image>
							</view>
						</view>
					</view>
				</scroll-view>

			</view>
		</mbtiPop>

	</view>
</template>

<script>
	import mBack from "@/components/m-back/index.vue"
	import mbtiModal from "@/components/m-mbti/modal.vue"
	import mbtiPop from "@/components/m-mbti/mbti-pop.vue"
	import {
		getFirendGroupDetail,
		updateGroupName,
		deleteFirendGroupById,
		toTopGroup,
		addFirendToGroup,
		deleteGroupFriend,
		getFriendList,
		createFirendGroup
	} from "@/api/mbti.js"
	import {
		getMbtiSourceByKey
	} from "@/utils/mbti-source"

	export default {
		components: {
			mBack,
			mbtiModal,
			mbtiPop
		},
		data() {
			return {
				createForm: {
					friendGroup: "",
					hasTop: 1,
					friendRelationshipId: [],
				},

				groupData: null,

				popCallBackFunction: null,
				actDeleteType: "",
				subMemberIds: [],
				newAddMemberIds: [],
				oldMemberIds: [],

				actControlType: "",
				hideBack: false,
				bgUrl: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/d394a848c52a40a0b7fc9baf22ba6a01.png",
				screenWidth: 375,
				rpxMenuButtonHeight: 64,
				rpxMenuButtonTop: 100,
				contentTop: 300,
				isOpen: true,
				isChoosed: false,
				id: null,
				groupName: "",
				memberList: [],
				// 过滤过的好友列表，全部都在，只不过已经添加到组中的会无法添加
				firendList: [],
				controlList: [{
						type: 'add',
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/bef01b74f2434b84aa61537074393c69.png"
					},
					{
						type: 'sub',
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/bca596dcfba240189af5e2204200c242.png"
					},
				]
			}
		},
		watch: {
			newAddMemberIds: {
				handler(newVal, oldVal) {
					if (this.$refs.mbtiPop) {
						if (newVal.length) {
							this.$refs.mbtiPop.handleControlConfirm(true)

						} else {
							this.$refs.mbtiPop.handleControlConfirm(false)
						}
					}
				},
				deep: true
			},
			subMemberIds: {
				handler(newVal, oldVal) {
					if (this.$refs.mbtiPop) {
						if (newVal.length) {
							this.$refs.mbtiPop.handleControlConfirm(true)
						} else {
							this.$refs.mbtiPop.handleControlConfirm(false)
						}
					}
				},
				deep: true,
			}

		},
		computed: {
			addOrSubData() {
				if (this.actControlType == 'add') {
					return this.firendList
				} else {
					return this.memberList
				}
			}
		},
		onLoad(e) {
			let {
				id,
				groupLength
			} = e
			if (id) {
				this.id = id
				this.loadData()
			} else {
				let length = Number(groupLength) + 1
				this.groupName = "分组" + length
				this.handleGetFirendList()
			}

		},
		created() {
			// this.handleGetFirendsData()
			try {
				let screenWidth = uni.getStorageSync('screenWidth')
				if (screenWidth) {
					this.screenWidth = screenWidth
				} else {
					this.screenWidth = uni.getSystemInfoSync().screenWidth; // 当前设备屏幕宽度
					uni.setStorageSync("screenWidth", this.screenWidth)
				}
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				let {
					top,
					height
				} = menuButtonInfo

				let rpxHeight = this.pxToRpx(height)
				let rpxTop = this.pxToRpx(top)
				this.rpxMenuButtonHeight = rpxHeight
				this.rpxMenuButtonTop = rpxTop
				this.contentTop = rpxTop + rpxHeight + 72

			} catch (error) {
				//TODO handle the exception
			}
		},

		methods: {
			pxToRpx(px) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / this.screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			handleBack() {
				uni.navigateBack()
			},
			loadData() {
				this.handleGetFirendList()
				this.handleGetFirendGroupDetail()
			},
			handleCreateFirendGroup() {
				if (!this.groupName) {
					uni.showToast({
						title: "分组名称必填",
						icon: "none"
					})
					return
				} else if (!this.createForm.friendRelationshipId.length) {
					uni.showToast({
						title: "好友不可为空",
						icon: "none"
					})
					return
				}


				this.createForm.friendGroup = this.groupName
				createFirendGroup(this.createForm).then(res => {
					// console.log("创建分组",res);
					// 获取分组id，this.id = id  然后 this.loadData()
					uni.showToast({
						title: "创建成功",
						icon: 'none'
					})
					setTimeout(() => {
						this.handleBack()
					}, 500)
				})
			},
			handleGetFirendList() {
				getFriendList().then(res => {
					let list = res.data.data
					let code = res.data.code
					// if (code == '401') {
					// 	this.handleGetFirendList()
					// 	return
					// }
					this.firendList = list.map((item, index) => {
						let source = getMbtiSourceByKey(item.mbti)
						let remark = item.remark ? item.remark : item.friendName
						let mbtiAvatar = ""
						if (source) {
							mbtiAvatar = source.smallAvatar
						}
						return {
							id: item.id,
							friendGroupMappingId: item.friendGroupMappingId,
							name: remark,
							avatar: item.headUrl,
							mbtiAvatar,
						}
					})

				})

			},
			handleAddFirendToGroup() {
				if (this.id) {
					addFirendToGroup({
						groupId: this.id,
						friendRelationshipId: this.newAddMemberIds
					}).then(res => {
						this.newAddMemberIds = []
						this.loadData()
						uni.showToast({
							title: "添加成功",
							icon: "none"
						})
					})
				} else {
					this.firendList.forEach((item, index) => {
						if (this.newAddMemberIds.includes(item.id)) {
							this.memberList.push(item)
						}
					})
					this.oldMemberIds = this.memberList.map((item, index) => {
						return item.id
					})
					this.createForm.friendRelationshipId = this.oldMemberIds
					this.newAddMemberIds = []
				}

			},
			handleDeleteGroupFirends() {
				if (this.id) {
					let subIds = this.memberList.filter((item, index) => {
						return this.subMemberIds.includes(item.id)
					}).map((item, index) => {
						return item.friendGroupMappingId
					})

					deleteGroupFriend(subIds).then(res => {
						this.subMemberIds = []
						this.loadData()
						uni.showToast({
							title: "删除成功",
							icon: "none"
						})
					})
				} else {
					this.deleteByIdsQueue(this.memberList, this.subMemberIds)
					this.oldMemberIds = this.memberList.map((item, index) => {
						return item.id
					})
					this.createForm.friendRelationshipId = this.oldMemberIds
					this.subMemberIds = []
				}

			},
			handleToTopGroup() {
				toTopGroup(this.id).then(res => {
					uni.showToast({
						title: "置顶成功",
						icon: "none"
					})
					this.loadData()

				})
			},
			handleDeleteFirendGroupById() {
				deleteFirendGroupById(this.id).then(res => {
					uni.showToast({
						title: "已解散",
						icon: "none"
					})
					setTimeout(() => {
						this.handleBack()
					}, 500)
				})
			},
			handleUpdateGroupName(groupName) {
				updateGroupName({
					id: this.id,
					friendGroup: groupName
				}).then(res => {
					uni.showToast({
						title: "修改成功",
						icon: "none"
					})
					this.loadData()
				})
			},
			handleGetFirendGroupDetail() {
				getFirendGroupDetail(this.id).then(res => {
					let data = res.data.data
					let code = res.data.code
					if (code == '401') {
						this.handleGetFirendGroupDetail()
						return
					}
					if (!data) {
						return
					}
					this.groupData = data
					this.groupName = data.friendGroup
					this.isChoosed = data.hasTop === 0 ? true : false
					this.memberList = data.friendRelationshipList.map((item, index) => {
						let source = getMbtiSourceByKey(item.mbti)
						let remark = item.remark ? item.remark : item.friendName
						let mbtiAvatar = ""
						if (source) {
							mbtiAvatar = source.smallAvatar
						}
						return {
							id: item.id,
							friendGroupMappingId: item.friendGroupMappingId,
							name: remark,
							avatar: item.headUrl,
							mbtiAvatar,
						}
					})
					this.oldMemberIds = this.memberList.map((item, index) => {
						return item.id
					})

				})
			},

			handlePopCallBack(callback) {
				if (this.subMemberIds.length == this.memberList.length) {
					// 成员删除如果要全部
					// this.handleDeleteGroupModalOpen('all-member-delete')
					// this.popCallBackFunction = callback
					callback(true)
				} else {
					callback(true)
				}
			},
			handleModalCancel() {
				this.hideBack = false
				if (this.actDeleteType == 'all-member-delete') {
					let callback = this.popCallBackFunction
					callback(false)
				}
			},
			handlePopCancel() {
				this.hideBack = false
				if (this.actControlType == 'add') {
					this.newAddMemberIds = []
				} else if (this.actControlType == 'sub') {
					this.subMemberIds = []
				}
			},
			deleteByIdsQueue(arr, ids) {
				let queue = ids.map(id => arr.findIndex(item => item.id === id))
					.filter(i => i !== -1);
				while (queue.length > 0) {
					const currentIndex = queue.shift();
					if (currentIndex >= 0 && currentIndex < arr.length) {
						arr.splice(currentIndex, 1);
						// 动态更新队列中未处理的索引（因删除导致后续元素索引-1）
						queue = queue.map(i => i > currentIndex ? i - 1 : i);
					}
				}
				return arr;
			},
			handleSettingConfirm(e) {
				if (this.actControlType == 'settingGroupName') {
					let data = e.data[0]
					if (this.id) {
						this.handleUpdateGroupName(data.value)
					} else {
						this.groupName = data.value
					}
				} else if (this.actControlType == 'add') {
					this.handleAddFirendToGroup()
				} else if (this.actControlType == 'sub') {
					this.handleDeleteGroupFirends()

				}

				this.hideBack = false

			},
			handleAddOrSubGroup(item, index) {
				if (this.actControlType == 'add') {
					if (!this.oldMemberIds.includes(item.id)) {
						if (!this.newAddMemberIds.includes(item.id)) {
							this.newAddMemberIds.push(item.id)
						} else {
							let cindex = this.newAddMemberIds.findIndex(e => {
								return item.id == e
							})
							this.newAddMemberIds.splice(cindex, 1)
						}
					}
				} else if (this.actControlType == 'sub') {
					if (!this.subMemberIds.includes(item.id)) {
						this.subMemberIds.push(item.id)
					} else {
						let index = this.subMemberIds.findIndex(e => {
							return item.id == e.id
						})
						this.subMemberIds.splice(index, 1)
					}
				}


			},

			handleControlBtnClick(type) {
				this.actControlType = type
				if (type == 'add') {
					// this.handleAddFirendToGroup()
					// return
					this.$refs.mbtiPop.open({
						data: [],
						title: `添加“${this.groupName}”组员`,
						code: 'add-to-group'
					})
				} else if (type == 'sub') {
					this.$refs.mbtiPop.open({
						data: [],
						title: `删减“${this.groupName}”组员`,
						code: 'sub-group',
						needCallBack: true
					})
				} else if (type == "settingGroupName") {
					this.$refs.mbtiPop.open({
						data: [{
								value: this.groupName,
								type: "label-none",
								valueType: "text",
								isRequire: true,
								limit: 18
							},

						],
						title: `修改拍一拍组名`,
					})

				}
				this.hideBack = true
			},
			handleDeleteConfirm(e) {
				this.hideBack = false
				// 如果确定删除 要走接口的
				// if (this.actDeleteType == "all-member-delete") {
				// 	let callback = this.popCallBackFunction
				// 	callback(true)
				// 	this.memberList = []
				// }
				this.handleDeleteFirendGroupById()
			},
			handleBottomBtnClick() {
				if (this.id) {
					this.handleDeleteGroupModalOpen()
				} else {
					// 创建分组
					this.handleCreateFirendGroup()
				}

			},
			handleDeleteGroupModalOpen(type) {
				this.actDeleteType = type
				this.$refs.mbtiModal.open({
					canCaleBtnName: "取消",
					confirmBtnName: "删除",
					title: `解散“${this.groupName}”组？`,
					type: "control",
				})
				this.hideBack = true
			},
			handleGroupChooseClick() {
				if (this.id) {
					this.handleToTopGroup()
				} else {
					this.isChoosed = !this.isChoosed
					this.createForm.hasTop = !this.isChoosed ? 1 : 0
				}

			},
			open(e) {
				let {
					id
				} = e
			}

		}
	}
</script>

<style lang="scss" scoped>
	.mbti-group-detail {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100%;
		height: 100%;
		background-color: #ededed;
		box-sizing: border-box;
		z-index: 99999;

		.mbti-group-detail-content {
			width: 100%;
			height: 100%;
			background-repeat: no-repeat;
			background-size: cover;
			background-position: center center;
			padding: 0rpx 48rpx;

			.top-box {
				width: 100%;
			}

			.content-box {
				width: 100%;
				flex: 1;
				overflow: hidden;
			}

			.group-member-list {
				width: 100%;
				background-color: #fff;
				border-radius: 20rpx;
				margin-bottom: 40rpx;
				padding-left: 38rpx;
				padding-bottom: 32rpx;
				flex-wrap: wrap;

				.group-member-item {
					position: relative;
					width: 92rpx;
					margin-top: 36rpx;
					margin-right: 30rpx;

					.group-member-avatar {
						position: relative;
						width: 92rpx;
						height: 92rpx;
						border-radius: 50%;
						margin-bottom: 12rpx;

					}

					.group-mbti-avatar {
						position: absolute;
						bottom: 0rpx;
						right: 0rpx;
						width: 36rpx;
						height: 36rpx;
						border: 3rpx solid #fff;
						border-radius: 50%;
					}

					.member-name {
						position: relative;
						width: 100%;
						height: 28rpx;
						font-weight: 400;
						font-size: 20rpx;
						color: #979797;
						line-height: 28rpx;
						text-align: center;

						.member-name-content {
							width: 120rpx;
							height: 28rpx;
							white-space: nowrap;
							text-overflow: ellipsis;
							overflow: hidden;
						}

					}
				}
			}

			.group-set {
				width: 100%;
				background-color: #fff;
				border-radius: 20rpx;

				.group-set-item {
					width: 100%;
					height: 116rpx;
					padding: 0rpx 28rpx;

					.group-set-item-content {
						position: relative;
						width: 100%;
						height: 100%;

						&::after {
							content: "";
							position: absolute;
							left: 0rpx;
							bottom: 0rpx;
							width: 100%;
							height: 0.5rpx;
							background-color: #ebebeb;
						}
					}

					.group-set-item-inner {
						flex: 1;
						height: 100%;
						margin-right: 28rpx;

						.group-set-item-label {
							height: 100%;
							font-weight: 300;
							font-size: 32rpx;
							color: #494949;
						}

						.group-set-item-text {
							flex: 1;
							height: 100%;
							font-weight: 400;
							font-size: 32rpx;
							color: #ebebeb;
							line-height: 40rpx;
						}

						.group-set-item-text-value {
							color: #494949;
						}
					}

					.group-choose-btn {
						width: 32rpx;
						height: 32rpx;
						border: 2rpx solid #CECECE;
						border-radius: 50%;
					}

					.btn-choosed {
						background-color: #6DD400;
						border-color: #B0FF5C;
					}


					&:last-child {
						.group-set-item-content {
							&::after {
								display: none;
							}
						}
					}
				}
			}

			.group-bottom-control {
				position: absolute;
				left: 0rpx;
				bottom: 240rpx;
				width: 100%;
				height: 104rpx;
				padding: 0rpx 48rpx;

				.group-bottom-control-content {
					width: 100%;
					height: 100%;
					border-radius: 20rpx;
					background-color: #fff;
					font-weight: 400;
					font-size: 32rpx;
					color: #E02020;
					line-height: 44rpx;
				}

				.group-create {
					color: #153135;
				}
			}
		}

	}

	.firend-list {
		width: 100%;
		height: 100%;
		overflow: hidden;

		.scroll-content {
			::-webkit-scrollbar {
				display: none !important;
			}
		}

		.firend-list-content {
			width: 100%;
		}

		.firend-item {
			width: 100%;
			height: 140rpx;
			background-color: #fff;
			border-radius: 20rpx;
			margin-bottom: 24rpx;

			.firend-avatar {
				width: 92rpx;
				height: 92rpx;
				border-radius: 50%;
				margin-left: 28rpx;
				margin-right: 20rpx;
			}

			.firend-name {
				flex: 1;
				font-weight: 400;
				font-size: 32rpx;
				color: #494949;
				line-height: 44rpx;
				margin-right: 36rpx;
			}

			.firend-control {
				width: 48rpx;
				height: 48rpx;
				margin-right: 36rpx;
				border-radius: 50%;
			}


		}
	}

	.right-control-icon {
		width: 12rpx;
		height: 20rpx;
	}
</style>